package com.zxmzy.scaffold.core.ext

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import androidx.core.view.size
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.zxmzy.scaffold.core.decoration.CustomDividerItemDecoration
import com.zxmzy.scaffold.core.decoration.GridSpaceItemDecoration

/**
 * @author zhangxiaoming
 * @date 2023/7/27
 * @description
 */

/**
 * 设置分割线
 * @param color 分割线的颜色，默认是#DEDEDE
 * @param size 分割线的大小，默认是1px
 * @param includeLast 最后一条是否绘制
 */
fun RecyclerView.divider(
    color: Int = Color.parseColor("#DEDEDE"),
    size: Int = 1,
    includeLast: Boolean = true
): RecyclerView {
    val decoration = CustomDividerItemDecoration(context, orientation)
    decoration.setDrawable(GradientDrawable().apply {
        setColor(color)
        shape = GradientDrawable.RECTANGLE
        setSize(size, size)
    })
    decoration.isDrawLastPositionDivider(includeLast)
    if (itemDecorationCount > 0) {
        removeItemDecorationAt(0)
    }
    addItemDecoration(decoration)
    return this
}

/**
 * 设置网格分割线间隔
 * @param spanCount 网格的列数
 * @param spacingDp 分割线的大小
 * @param includeEdge 是否包含边缘
 *
 */
fun RecyclerView.dividerGridSpace(
    spanCount: Int,
    spacingSize: Int,
    includeEdge: Boolean
): RecyclerView {
    addItemDecoration(GridSpaceItemDecoration(spanCount, spacingSize, includeEdge))
    return this
}

fun RecyclerView.vertical(spanCount: Int = 0, isStaggered: Boolean = false): RecyclerView {
    layoutManager = if (spanCount > 0) {
        if (isStaggered) {
            StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL)
        } else {
            GridLayoutManager(context, spanCount)
        }
    } else {
        LinearLayoutManager(context, RecyclerView.VERTICAL, false)
    }
    return this
}

fun RecyclerView.horizontal(spanCount: Int = 0, isStaggered: Boolean = false): RecyclerView {
    layoutManager = if (spanCount != 0) {
        if (isStaggered) {
            StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.HORIZONTAL)
        } else {
            GridLayoutManager(context, spanCount, GridLayoutManager.HORIZONTAL, false)
        }
    } else {
        LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
    }
    return this
}

inline val RecyclerView.orientation
    get() = if (layoutManager == null) -1 else layoutManager.run {
        when (this) {
            is LinearLayoutManager -> orientation
            is GridLayoutManager -> orientation
            is StaggeredGridLayoutManager -> orientation
            else -> -1
        }
    }
